package com.cg.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.cg.util.JoinUtil;
import com.cg.wechat.CoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * Created by Administrator on 2017/5/11.
 */
@Controller
@RequestMapping(value="/wechat")
public class WXCoreController {
    @Autowired
    private CoreService coreService;
    @RequestMapping(value="/portal")
    public void  wxCore(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        System.out.println("----------------------------start---------------------------");
        System.out.println("进入Controller......");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        PrintWriter print;
        if (isGet) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (signature != null && JoinUtil.checkSignature(signature, timestamp, nonce)) {
                try {
                    print = response.getWriter();
                    print.write(echostr);
                    System.out.print("接入成功true.........");
                    print.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            try {
                String s = coreService.dealResponse(request);
                PrintWriter writer = response.getWriter();
                writer.write(s);
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
